package com.tdam.CommunicationManager;



import java.util.ArrayList;
import java.util.Date;

import com.tdam.CommunicationManager.AnimatedActivity.InfoAdapter;

import android.app.ListActivity;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.telephony.PhoneNumberUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;

public class History extends AnimatedActivity
{
	private ArrayList<LogInfo> calls;
	private ArrayList<LogInfo> sms;
	private ArrayList<LogInfo> mails;
	private boolean editMode;
	private Button btmEdit;
	private LinearLayout lytDelete;
	private LinearLayout lnlOptions;
	private RadioButton rbtmAll;
	private RadioButton rbtmCalls;
	private RadioButton rbtmSms;
	private RadioButton rbtmMails;
	
	protected void onCreate(Bundle savedInstanceState) 
	{
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.history);
		_adapter = new InfoAdapter<LogInfo,LogInfoHolder>(this,
				R.layout.log_info_item,LogInfoHolder.class);
		getListView().setAdapter(_adapter);
		getListView().setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				if(editMode)onItemSelected(position);
			}
		});	
		calls=new ArrayList<LogInfo>();
		sms=new ArrayList<LogInfo>();
		mails=new ArrayList<LogInfo>();
		rbtmAll=(RadioButton)findViewById(R.id.rbtmAll);
		rbtmCalls=(RadioButton)findViewById(R.id.rbtmPhoneCalls);
		rbtmSms=(RadioButton)findViewById(R.id.rbtmSms);
		rbtmMails=(RadioButton)findViewById(R.id.rbtmMails);
		btmEdit=(Button) findViewById(R.id.btmEdit);
		lytDelete=(LinearLayout) findViewById(R.id.lytDelete);
		lnlOptions=(LinearLayout) findViewById(R.id.lnlOptions);
		Button btmDelete=(Button) findViewById(R.id.btmDelete);
		btmDelete.setOnClickListener(new OnClickListener() {   
			@Override
			public void onClick(View v) {
				onDelete();
			}
		});
		rbtmAll.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if(arg1)onAllSelected();
			}
		});

		rbtmCalls.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if(arg1)onCallsSelected();
			}
		});
		
		rbtmSms.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if(arg1)onSmsSelected();
			}
		});
		
		rbtmMails.setOnCheckedChangeListener(new OnCheckedChangeListener(){

			@Override
			public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
				if(arg1)onMailSelected();
			}
		});

		btmEdit.setOnClickListener(new OnClickListener() {   
			@Override
			public void onClick(View v) {
				if(editMode)
					onExitEditMode();
				else
					onEditMode();
				
			}
		});

		
		onAllSelected();
		editMode=false;
		 
	}

	@Override
	protected void onResume()
	{
		super.onResume();
        SharedPreferences prefs = PreferenceManager
        .getDefaultSharedPreferences(getBaseContext());
        switch(Integer.parseInt(prefs.getString("lstHistoryFilter","1")))
        {
        case 1:
        	rbtmAll.performClick();
        	break;
        case 2:
        	rbtmCalls.performClick();
        	break;
        case 3:
        	rbtmSms.performClick();
        	break;
        case 4:
        	rbtmMails.performClick();
        }
        _adapter.notifyDataSetChanged();
	}
	
	
	
	private void onExitEditMode()
	{
		editMode=false;
		btmEdit.setText(getString(R.string.edit));
		lnlOptions.setVisibility(View.VISIBLE);
		lytDelete.setVisibility(View.GONE);
		int elementsCounter=_adapter.getAllCount()-1;
		for(;elementsCounter>-1;--elementsCounter)
			((LogInfo)_adapter.getItemFromOriginal(elementsCounter)).edit=EditStatus.NOT_EDIT;
		_adapter.notifyDataSetChanged();

	}
	
	private void onEditMode()
	{
		editMode=true;
		btmEdit.setText(getString(R.string.End));
		lytDelete.setVisibility(View.VISIBLE);
		lnlOptions.setVisibility(View.GONE);
		int elementsCounter=_adapter.getAllCount()-1;
		for(;elementsCounter>-1;--elementsCounter)
			((LogInfo)_adapter.getItemFromOriginal(elementsCounter)).edit=EditStatus.EDIT_NOT_MARKED;
		_adapter.notifyDataSetChanged();
		
	}	
	
	private void loadCalls()
	{
		 calls.clear();
		 Cursor callLogCursor = getContentResolver().query(
                 CallLog.Calls.CONTENT_URI,
                 null, null, null,
                 CallLog.Calls.DEFAULT_SORT_ORDER);
		 
		 while(callLogCursor.moveToNext())
		 {
			 String name=callLogCursor.getString(callLogCursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
			 LogInfo newLog = new LogInfo(callLogCursor.getInt(callLogCursor.getColumnIndex
					 (CallLog.Calls.TYPE)),callLogCursor.getString(callLogCursor.getColumnIndex
					 (CallLog.Calls.NUMBER)),(name!=null)?name:getString(R.string.unknown)
					 ,new Date(callLogCursor.getLong(callLogCursor.getColumnIndex(CallLog.Calls.DATE))));
			  calls.add(newLog);
		 }		
	}
	
	private void loadSms()
	{
		 sms.clear();
		 Cursor smsLogCursor = getContentResolver().query(
                 Uri.parse("content://sms"),
                 null, null, null,
                 null);
		 while(smsLogCursor.moveToNext())
		 {
			 String contactName=getString(R.string.unknown);
		 
		        Cursor cur = getContentResolver().query(Phone.CONTENT_URI,
		                null, Phone.NUMBER + "=?", 
		                new String[]{PhoneNumberUtils.formatNumber(smsLogCursor.getString
		                		(smsLogCursor.getColumnIndex("address")))}, null);
		        if (cur.moveToNext()) 
		        {
		            Cursor contactCursor= getContentResolver().query(ContactsContract.
		            		Contacts.CONTENT_URI,null, ContactsContract.Contacts._ID + "=?",
		            		new String[]{cur.getString(cur.getColumnIndex(Phone.RAW_CONTACT_ID))}, null);
		            if (contactCursor.moveToNext()) 
		        		contactName=contactCursor.getString(contactCursor.getColumnIndex
		        				(ContactsContract.Contacts.DISPLAY_NAME));
		        }			 
			 
		 
			 LogInfo newLog=new LogInfo(smsLogCursor.getInt(smsLogCursor.getColumnIndex("type"))+10,
					  smsLogCursor.getString(smsLogCursor.getColumnIndex("address")),contactName,
					  new Date(smsLogCursor.getLong(smsLogCursor.getColumnIndex("date"))));
			 sms.add(newLog);
		 }		
	}
	
	private void loadMails()
	{
		mails.clear();
//		 Cursor emailsLogCursor = getContentResolver().query(
//                 Uri.parse("content://email"),
//                 null, null, null,
//                 null);
//		 while(emailsLogCursor.moveToNext())
//		 {
//			 String columnNames[]=emailsLogCursor.getColumnNames();
//			 StringBuilder params=new StringBuilder();
//			 for(String column :columnNames)
//			 {
//				 params.append(emailsLogCursor.getString(emailsLogCursor.getColumnIndex(column)));
//				 params.append("|");
//				 LogInfo newLog=new LogInfo(0,column,emailsLogCursor.getString(emailsLogCursor.
//						 getColumnIndex(column)), new Date());
//				 mails.add(newLog);
//			 }		
//		 }
	}
	
	private void onItemSelected(int position)
	{
		LogInfo temp=(LogInfo)_adapter.getItem(position);
		temp.edit=(temp.edit==EditStatus.EDIT_NOT_MARKED)?EditStatus.EDIT_MARKED:EditStatus.EDIT_NOT_MARKED;
		_adapter.notifyDataSetChanged();		
	}
	
	private void onAllSelected()
	{
		loadCalls();
		loadSms();
		loadMails();
		_adapter.clear();
		for(LogInfo log:calls)_adapter.addItem(log);
		for(LogInfo log:sms)_adapter.addItem(log);
		for(LogInfo log:mails)_adapter.addItem(log);
		_adapter.sort(new LogDateComparator());
		_adapter.notifyDataSetChanged();
	}

	private void onCallsSelected()
	{
		loadCalls();
		_adapter.clear();
		for(LogInfo log:calls)_adapter.addItem(log);
		_adapter.sort(new LogDateComparator());
		_adapter.notifyDataSetChanged();
	}
	
	private void onSmsSelected()
	{
		loadSms();
		_adapter.clear();
		for(LogInfo log:sms)_adapter.addItem(log);
		_adapter.sort(new LogDateComparator());
		_adapter.notifyDataSetChanged();
	}
	
	private void onMailSelected()
	{
		loadMails();
		_adapter.clear();
		for(LogInfo log:mails)_adapter.addItem(log);
		_adapter.sort(new LogDateComparator());
		_adapter.notifyDataSetChanged();
	}
	
	private void onDelete()
	{
		int elementsCounter=_adapter.getCount()-1;
		LogInfo temp;
		for(;elementsCounter>-1;--elementsCounter)
		{
			temp=(LogInfo)_adapter.getItem(elementsCounter);
			if(temp.edit==EditStatus.EDIT_MARKED)
			{
				switch(temp.type)
				{
				case LogInfo.INCOMING:
				case LogInfo.OUTGOING:
				case LogInfo.MISSED:
					getContentResolver().delete(CallLog.Calls.CONTENT_URI,
							CallLog.Calls.TYPE + "=? AND " +
							CallLog.Calls.NUMBER + "=? AND " +
							CallLog.Calls.DATE + "=?", 
			                new String[]{String.valueOf(temp.type),temp.number,
							String.valueOf(temp.date.getTime())});
					break;	
				case LogInfo.SMS_RECEIVED:
				case LogInfo.SMS_SEND:
					getContentResolver().delete(Uri.parse("content://sms"),
							"type=? AND " +
							"address=? AND " +
							"date=?", 
			                new String[]{String.valueOf(temp.type-10),temp.number,
							String.valueOf(temp.date.getTime())});
					break;
				}
				_adapter.remove(elementsCounter);
			}
				
		}
			
		_adapter.notifyDataSetChanged();				
	}
}
